//
//  MainItemDetailVC.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/12.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import HGPlaceholders
import SCLAlertView
import SVProgressHUD

class MainItemDetailVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    
    var materialId: Int!
    let helper = MaterialHelper()
    var material: MaterialDetail!
    let sectionTitles = [nil, "自定义录入项", "色板图片", "成分", "详情图片", "商品相关图"]
    @IBOutlet weak var tableView: TableView!
    @IBOutlet weak var collectionView: UICollectionView!
    
    func requestData() {
        tableView.showLoadingPlaceholder()
        helper.getMaterialDetail(with: materialId) { (error, material) in
            guard error == nil else {
                self.tableView.showErrorPlaceholder()
                return
            }
            self.material = material!
            self.tableView.showDefault()
            self.collectionView.isHidden = false
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.placeholderDelegate = self
        material = MaterialDetail()
        tableView.delegate = self
        tableView.dataSource = self
        collectionView.delegate = self
        collectionView.dataSource = self
        tableView.contentInset = UIEdgeInsetsMake(0, 0, 100, 0)
        requestData()
        
        tableView.register(UINib(nibName: "TextCell", bundle: nil), forCellReuseIdentifier: "TextCell")
        tableView.register(UINib(nibName: "ColorCell", bundle: nil), forCellReuseIdentifier: "ColorCell")
        tableView.register(UINib(nibName: "ComponentCell", bundle: nil), forCellReuseIdentifier: "ComponentCell")
        tableView.register(UINib(nibName: "OneImageCell", bundle: nil), forCellReuseIdentifier: "OneImageCell")
        tableView.register(UINib(nibName: "ImageCell", bundle: nil), forCellReuseIdentifier: "ImageCell")
        
        collectionView.register(UINib(nibName: "MainItemCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "MainItemCollectionViewCell")
        
        let editItem = UIBarButtonItem(title: "编辑", style: .plain, target: self, action: #selector(editBarBtTapped(_:)))
        let managerItem = UIBarButtonItem(title: "管理", style: .plain, target: self, action: #selector(managerBarBtTapped(_:)))
        navigationItem.setRightBarButtonItems([managerItem, editItem], animated: true)
    }
    @objc func editBarBtTapped(_ button: UIBarButtonItem!) {
        let editVC = EditMaterialVC(style: .grouped)
        editVC.materialDetail = material
        editVC.delegate = self
        let nav = UINavigationController(rootViewController: editVC)
        self.present(nav, animated: true, completion: nil)
    }
    
    @objc func managerBarBtTapped(_ button: UIBarButtonItem!) {
        let alertVC = UIAlertController(title: "物料管理", message: nil, preferredStyle: .alert)
        alertVC.addAlert("商品入库记录") { [weak self] (_) in
            let rukuRecordVC = RuKuRecordVC()
            rukuRecordVC.materialId = self?.materialId
            self?.navigationController?.pushViewController(rukuRecordVC, animated: true)
        }
        alertVC.addAlert("商品共享记录") { [weak self] (_) in
            let shareRecordVC = ShareRecordVC()
            shareRecordVC.materialId = self?.materialId
            self?.navigationController?.pushViewController(shareRecordVC, animated: true)
        }
        alertVC.addAlert("索版记录") { [weak self] (_) in
            let suobanRecordVC = SuoBanVC()
            suobanRecordVC.materialId = self?.materialId
            self?.navigationController?.pushViewController(suobanRecordVC, animated: true)
        }
        alertVC.addAlert("销售记录") { [weak self] (_) in
            let saleRecordVC = SaleRecordVC()
            saleRecordVC.materialId = self?.materialId
            self?.navigationController?.pushViewController(saleRecordVC, animated: true)
        }
        alertVC.addAlert("类同物料管理") { (_) in
            
        }
        alertVC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        self.present(alertVC, animated: true, completion: nil)
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 6
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 8
        } else if section == 1{
            guard let userDefine = material.userDefine else {
                return 1
            }
            return userDefine.count
        } else {
            return 1
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let lingMai = material.lingMaiPrice == nil ? "否" : material.lingMaiPrice!
            let suoBan = material.suoBan == 0 ? "否" : "是"
            let listValues = [material.name, material.no, material.attr, material.price, material.unit, "\(material.stock)", lingMai, suoBan]
            let lists = ["名称", "货号", "品类", "单价", "单位", "库存量", "零卖", "索版"]
            let cell = tableView.dequeueReusableCell(withIdentifier: "TextCell") as! TextCell
            cell.titleLabel.text = lists[indexPath.row]
            cell.textField.text = listValues[indexPath.row]
            cell.edited = false
            
            return cell
        } else if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "TextCell") as! TextCell
            if material.userDefine == nil {
                cell.titleLabel.text = "自定义项目"
                cell.textField.text = "暂无"
            } else {
                cell.titleLabel.text = material.userDefine![indexPath.row].key
                cell.textField.text = material.userDefine![indexPath.row].value
            }
            cell.edited = false
            return cell
        } else if indexPath.section == 
            2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ColorCell") as! ColorCell
            var images = [Any]()
            var items = [ColorOfMaterial]()
            for color in material.color {
                images.append(color.picture)
                items.append(ColorOfMaterial(no: color.no, color: color.color, strock: color.stock))
            }
            cell.images = images
            cell.items = items
            
            cell.edited = false
            return cell
        } else if indexPath.section == 3 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ComponentCell") as! ComponentCell
            cell.items = material.component
            cell.edited = false
            return cell
        } else if indexPath.section == 4 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "OneImageCell") as! OneImageCell
            if let url = URL(string: material.body) {
                cell.imgView.kf.setImage(with: url)
            } else {
                cell.imgView.image = UIImage(named: "")
            }
            cell.edited = false
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ImageCell") as! ImageCell
            var images = [Any]()
            for item in material.picture {
                images.append(item.img)
            }
            cell.images = images
            cell.edited = false
            return cell
        }
        
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sectionTitles[section]
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 || indexPath.section == 1 {
            return 50
        } else if indexPath.section == 4 {
            return 200
        }
        else {
            return 110
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}
extension MainItemDetailVC: PlaceholderDelegate {
    func view(_ view: Any, actionButtonTappedFor placeholder: Placeholder) {
        if placeholder.key == .loadingKey {
            navigationController?.popViewController(animated: true)
        } else if placeholder.key == .errorKey {
            requestData()
        }
    }
}

extension MainItemDetailVC: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MainItemCollectionViewCell", for: indexPath) as! MainItemCollectionViewCell
        let listTitles = ["二维码","商品入库", "商品销售", "商品共享", "索物料版", "零卖散剪"]
        cell.titleLabel.text = listTitles[indexPath.row]
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.row == 0 { // 二维码
            print(material.id)
            let image = generateQRCode(from: "material:\(material.id)", scale: 5)
            let a = AlertController(title: "", message: nil, preferredStyle: .alert)
            a.setTitleImage(image)
            let action = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            a.addAction(action)
            self.present(a, animated: true, completion: nil)
        } else if indexPath.row == 1 {
            let rukuVC = RuKuVC()
            rukuVC.material = material
            rukuVC.delegate = self
            navigationController?.pushViewController(rukuVC, animated: true)
        } else if indexPath.row == 2 {
            let xiaoshouVC = XiaoShouVC()
            xiaoshouVC.material = material
            navigationController?.pushViewController(xiaoshouVC, animated: true)
        } else if indexPath.row == 3 { //商品共享
            
        }  else if indexPath.row == 4 {
            let appearence = SCLAlertView.SCLAppearance(showCloseButton: false, shouldAutoDismiss: false, hideWhenBackgroundViewIsTapped: false)
            let alert = SCLAlertView(appearance: appearence)
            func handlerSuoBan(with status: Int) {
                self.view.isUserInteractionEnabled = false
                SVProgressHUD.show()
                self.helper.setSuoBan(with: self.materialId, status: status, completeHandler: { (error) in
                    self.view.isUserInteractionEnabled = true
                    if error != nil {
                        SVProgressHUD.showError(withStatus: error.debugDescription)
                    }
                    alert.hideView()
                    SVProgressHUD.dismiss(withDelay: 1.0)
                    self.material.suoBan = status
                    self.tableView.beginUpdates()
                    self.tableView.reloadRows(at: [IndexPath(row: 7, section: 0)], with: .automatic)
                    self.tableView.endUpdates()
                })
            }
            alert.addButton("是", action: {
                handlerSuoBan(with: 1)
            })
            alert.addButton("否", action: {
                handlerSuoBan(with: 0)
            })
            alert.addButton("取消", action: {
                self.view.isUserInteractionEnabled = true
                alert.hideView()
            })
            alert.showNotice("是否提供物料样板", subTitle: "选择是或否，或者取消")
        } else if indexPath.row == 5 {
            let appearence = SCLAlertView.SCLAppearance(showCloseButton: false, shouldAutoDismiss: true, hideWhenBackgroundViewIsTapped: false)
            let alert = SCLAlertView(appearance: appearence)
            func handlerLingMai(with status: Int) {
                if status == 0 {
                    SVProgressHUD.show()
                    self.helper.setLingMain(with: self.materialId, status: 1, price: nil, completeHandler: { (error) in
                        if error != nil {
                            SVProgressHUD.showError(withStatus: error.debugDescription)
                        }
                        SVProgressHUD.dismiss(withDelay: 1.0)
                        self.material.lingMai = 0
                        self.material.lingMaiPrice = nil
                        self.tableView.beginUpdates()
                        self.tableView.reloadRows(at: [IndexPath(row: 6, section: 0)], with: .automatic)
                        self.tableView.endUpdates()
                    })
                } else {
                    let nextAppearence = SCLAlertView.SCLAppearance(showCloseButton: false, shouldAutoDismiss: true, hideWhenBackgroundViewIsTapped: false)
                    let nextAlert = SCLAlertView(appearance: nextAppearence)
                    let textField = nextAlert.addTextField("零卖散剪价格")
                    textField.keyboardType = .numberPad
                    nextAlert.addButton("确定", action: {
                        SVProgressHUD.show()
                        guard let text = textField.text.nilIfEmpty else {
                            return
                        }
                        guard let price = Double(text) else {
                            return
                        }
                        self.helper.setLingMain(with: self.materialId, status: 1, price: price, completeHandler: { (error) in
                            if error != nil {
                                SVProgressHUD.showError(withStatus: error.debugDescription)
                            }
                            SVProgressHUD.dismiss(withDelay: 1.0)
                            self.material.lingMai = 1
                            self.material.lingMaiPrice = text
                            self.tableView.beginUpdates()
                            self.tableView.reloadRows(at: [IndexPath(row: 6, section: 0)], with: .automatic)
                            self.tableView.endUpdates()
                        })
                    })
                    nextAlert.addButton("取消", action: {
                        nextAlert.hideView()
                    })
                    nextAlert.showNotice("输入零卖散剪价格", subTitle: "", animationStyle: .rightToLeft)
                }
            }
            alert.addButton("是", action: {
                handlerLingMai(with: 1)
            })
            alert.addButton("否", action: {
                handlerLingMai(with: 0)
            })
            alert.addButton("取消", action: {
                alert.hideView()
            })
            alert.showNotice("是否可以零卖散剪", subTitle: "选择是或否，或者取消")
        }
    }
}

extension MainItemDetailVC: RuKuVCDelegate {
    func didSuccess() {
        tableView.reloadData()
    }
}

extension MainItemDetailVC: EditMaterialDelegate {
    func didEditMaterial(with material: MaterialDetail) {
        self.material = material
        tableView.reloadData()
    }
}
